package v1

import (
	"strconv"

	"gitee.com/cyanbleeze/go-image-management/internal/service"
	"gitee.com/cyanbleeze/go-image-management/pkg/app"
	"gitee.com/cyanbleeze/go-image-management/pkg/errcode"
	"github.com/gin-gonic/gin"
)

type Picture struct{}

func NewPicture() Picture {
	return Picture{}
}

func (p Picture) Get(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Param("id"))
	res := app.NewResponse(ctx)
	if err != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	svc := service.New(ctx)
	d, err2 := svc.GetPicture(&service.PictureRequest{ID: uint(id)})
	if err2 != nil {
		res.ToErrorResponse(errcode.ErrorDeleteDetailFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(d)
}
func (p Picture) List(ctx *gin.Context) {
	params := service.PictureListRequest{}
	res := app.NewResponse(ctx)
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	pager := app.Pager{
		Page:     app.GetPage(ctx),
		PageSize: app.GetPageSize(ctx),
	}

	svc := service.New(ctx)
	detailList, count, err := svc.GetPictureList(&params, &pager)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorGetDetailListFail.WithDetails(err.Error()))
		return
	}
	res.ToResponseList(detailList, count)
}
func (p Picture) Create(ctx *gin.Context) {
	param := service.CreatePictureRequest{}
	res := app.NewResponse(ctx)
	valid, errs := app.BindAndValid(ctx, &param)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.CreatePicture(&param)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorCreateDetailFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}
func (p Picture) Update(ctx *gin.Context) {
	res := app.NewResponse(ctx)
	id, IDErr := strconv.Atoi(ctx.Param("id"))
	if IDErr != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(IDErr.Error()))
		return
	}
	params := service.UpdatePictureRequest{ID: uint(id)}
	valid, errs := app.BindAndValid(ctx, &params)
	if !valid {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(errs.Errors()...))
		return
	}
	svc := service.New(ctx)
	err := svc.UpdatePicture(&params)
	if err != nil {
		res.ToErrorResponse(errcode.ErrorUpdateDetailFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}
func (p Picture) Delete(ctx *gin.Context) {
	id, err := strconv.Atoi(ctx.Param("id"))
	res := app.NewResponse(ctx)
	if err != nil {
		res.ToErrorResponse(errcode.InvalidParams.WithDetails(err.Error()))
		return
	}
	svc := service.New(ctx)
	err2 := svc.DeletePicture(&service.DeletePictureRequest{ID: uint(id)})
	if err2 != nil {
		res.ToErrorResponse(errcode.ErrorDeleteDetailFail.WithDetails(err.Error()))
		return
	}
	res.ToResponse(gin.H{})
}
